<script setup lang="tsx">
defineOptions({
  name: "inspection"
});

import { ref, onActivated, onMounted, onUnmounted, markRaw, getCurrentInstance, inject, computed, nextTick, h } from "vue";
import { querySpecialtyConsumptionInspectionList, createInspection, createInspectionConfirm } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { formatTableDataFn, formatDateTableCloumnsFn } from "./hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import dayjs from "dayjs";
import { PxMessage, PxMessageBox } from "px-ui";
import ReTextTooltip from "@/components/ReTextTooltip";
// import { useThrottleFn } from "@vueuse/core";

const searchLoading = ref<boolean>(false);
const gap = 40;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const commonTableKey = ref<string>(Math.random().toString(36).slice(2, 10));
const tableData = ref<Array<any>>([]);

let defaultParams: any = {};
let currentParams: any = {};

const searchOption = ref<Array<CommonSearch.SearchOption>>([
  {
    label: "日期",
    key: "itemDate",
    value: dayjs().format("YYYY-MM-DD"),
    type: "date",
    props: {
      clearable: false,
      disabledDate: (d: Date) => {
        return dayjs(d).isAfter(dayjs(), "day");
      }
    },
    placeholder: "请选择日期"
  }
]);

const tableCloumns = computed(() => {
  const deviceCode = {
    label: "设备",
    prop: "deviceCode",
    fixed: "left",
    width: 120,
    render(scope) {
      const {
        row: { deviceCode = "", isInspectionPerson = false, isSystemEngineer = false }
      } = scope;
      const styleFn = () => {
        const textAlign = isInspectionPerson || isSystemEngineer ? "center" : "left";
        const fontWeight = isInspectionPerson || isSystemEngineer ? 600 : undefined;
        return { textAlign, fontWeight };
      };
      // return () => <div style={styleFn()}>{deviceCode || "--"}</div>;
      return () =>
        isInspectionPerson || isSystemEngineer ? (
          <div style={styleFn()}>{deviceCode || "--"}</div>
        ) : deviceCode ? (
          <div style={{ width: "100%" }}>
            <ReTextTooltip content={deviceCode} />
          </div>
        ) : (
          "--"
        );
    }
  };
  const checkItem = {
    label: "Check Item",
    prop: "checkItem",
    fixed: "left"
  };
  const specL = {
    label: "SPEC L",
    prop: "specL",
    fixed: "left"
  };
  const specU = {
    label: "SPEC U",
    prop: "specU",
    fixed: "left"
  };
  const dateList = formatDateTableCloumnsFn(tableData.value, inspectionFn, systemEngineerConfirmFn);
  return [deviceCode, checkItem, specL, specU, ...dateList];
});

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  const { isInspectionPerson, isSystemEngineer, rowspan, rowspan2 } = row;
  const { property } = column;
  if (isInspectionPerson || isSystemEngineer) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: 4
      };
    } else if (columnIndex < 4) {
      return {
        rowspan: 0,
        colspan: 0
      };
    } else if ((columnIndex - 4) % 3 === 0) {
      return {
        rowspan: 1,
        colspan: 3
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  } else if (property === "deviceCode") {
    return {
      rowspan: rowspan || 0,
      colspan: rowspan ? 1 : 0
    };
  } else if (property.includes("supplyStatus_")) {
    return {
      rowspan: rowspan2 || 0,
      colspan: rowspan2 ? 1 : 0
    };
  }
};

const rowStyleFn = ({ row, rowIndex }: CommonTable.RowType): Record<string, string> => {
  const { isFixed, isInspectionPerson, isSystemEngineer } = row;
  const style = {};
  if (isFixed) {
    // style["background"] = "var(--px-color-primary-light-9)";
    style["background"] = "#fff";
    style["position"] = "sticky";
    style["z-index"] = 2;
    style["bottom"] = isInspectionPerson ? "38px" : 0;
    style["height"] = "38px";
  }
  return style;
};

const rowClassNameFn = ({ row, rowIndex }: any): any => {
  const { isFixed, isInspectionPerson, isSystemEngineer } = row;
  if (isFixed) {
    return isInspectionPerson ? "inspection-fixed_1 inspection-fixed" : "inspection-fixed";
  } else {
    return "";
  }
};

const isNumberic = (val: any) => {
  if (typeof val === "number") {
    return true;
  } else if (typeof val === "string") {
    return /^[+-]?\d+(\.\d+)?$/.test(val);
  } else {
    return false;
  }
};

const cellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const { specL, specU, index = 0 } = row;
  const { property } = column;
  const style: any = {};
  if (isNumberic(row[property]) && isNumberic(specL) && isNumberic(specU)) {
    if (row[property] < Number(specL) || row[property] > Number(specU)) {
      style["background-color"] = "#EF4444";
      style["color"] = "#fff";
    } else if (index && index % 2 === 1) {
      style["background"] = "var(--px-color-primary-light-9)";
    }
  } else if (index && index % 2 === 1) {
    style["background"] = "var(--px-color-primary-light-9)";
  }
  return style;
};

const inspectionFn = async (scope: any) => {
  PxMessageBox.confirm("是否点检？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const {
      row: { itemDate }
    } = scope;
    const itemType = "SPECIALTY_GAS"; //   特气 SPECIALTY_GAS    大宗气 BULK_GAS    化学品 CHEMICAL
    const checkStatus = 1; //   点检类型：0未点检   1已点捡
    const params = { itemType, itemDate, checkStatus };
    await createInspection(params);
    PxMessage.success("点检成功！！");
    await queryTableDataFn();
  });
};

const systemEngineerConfirmFn = async (scope: any) => {
  PxMessageBox.confirm("是否确认点检？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const {
      row: { itemDate }
    } = scope;
    const itemType = "SPECIALTY_GAS"; //   特气 SPECIALTY_GAS    大宗气 BULK_GAS    化学品 CHEMICAL
    const checkStatus = 1; //   点检确认类型：0未确认  1已确认
    const params = { itemType, itemDate, checkStatus };
    await createInspectionConfirm(params);
    PxMessage.success("确认点检成功！！");
    await queryTableDataFn();
  });
};

const queryTableDataFn = async () => {
  searchLoading.value = true;
  tableData.value.splice(0);
  const params = { ...defaultParams, ...currentParams.value };
  const res = await querySpecialtyConsumptionInspectionList(params, () => {
    searchLoading.value = false;
  });
  tableData.value = formatTableDataFn(res);
  await nextTick();
  commonTableKey.value = Math.random().toString(36).slice(2, 10);
  await nextTick();
  setTimeout(() => {
    commonTableRef.value?.el?.setScrollLeft(2000);
    searchLoading.value = false;
  }, 0);
};

const submitSearchFormHandler = async (form: any) => {
  currentParams.value = { ...currentParams.value, ...form };
  await queryTableDataFn();
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div v-loading="searchLoading" class="inspection">
    <div class="inspection-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="4"
        :operationSpan="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="submitSearchFormHandler"
      />
    </div>
    <div ref="objectModelTableRef" class="inspection-table">
      <commonTable
        ref="commonTableRef"
        :key="commonTableKey"
        v-model="tableData"
        v-model:loading="searchLoading"
        :pagination="false"
        :height="scrollbarHeight"
        :tableCloumns="tableCloumns"
        :span-method="objectSpanMethod"
        :row-style="rowStyleFn"
        :row-class-name="rowClassNameFn"
        :cell-style="cellStyleFn"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.inspection {
  width: 100%;
  background-color: #fff;

  .inspection-search {
    width: 100%;
  }

  .inspection-table {
    margin-top: 16px;
  }
}

:deep(.px-table__body) {
  .inspection-fixed {
    td:first-child {
      border-left: var(--px-table-border);
    }
  }

  .inspection-fixed_1 {
    td {
      border-top: 1px solid #fff;
      box-shadow: 0 -3px 6px -3px #e2e2e2;
    }
  }
}
</style>
